package com.benjaminwan.read.free.ui.settings

import android.content.Context
import com.airbnb.mvrx.MvRxViewModelFactory
import com.airbnb.mvrx.ViewModelContext
import com.benjaminwan.read.free.base.viewmodel.MvRxViewModel
import com.benjaminwan.read.free.base.viewmodel.state
import com.benjaminwan.read.free.common.SP_VIBRATOR_ENABLE
import com.benjaminwan.read.free.common.SP_KEEP_SCREEN_ON
import com.benjaminwan.read.free.common.SP_SHOW_GUIDE
import com.benjaminwan.read.free.common.appPrefs
import com.benjaminwan.read.free.utils.moshiAny

class SettingsViewModel(
    initialState: SettingsState,
    val context: Context
) : MvRxViewModel<SettingsState>(initialState) {

    private var spIsShowGuide: Boolean by context.appPrefs.moshiAny(
        SP_SHOW_GUIDE, true
    )

    private var spKeepScreenOn: Boolean by context.appPrefs.moshiAny(
        SP_KEEP_SCREEN_ON, true
    )

    private var spVibratorEnable: Boolean by context.appPrefs.moshiAny(
        SP_VIBRATOR_ENABLE, true
    )

    init {
        setState {
            copy(
                isShowGuide = spIsShowGuide,
                keepScreenOn = spKeepScreenOn,
                vibratorEnable = spVibratorEnable
            )
        }
    }

    fun setKeepScreenOn(isEnable: Boolean) {
        setState {
            copy(keepScreenOn = isEnable)
        }
    }

    fun setIsShowGuide(isShow: Boolean) {
        spIsShowGuide = isShow
        setState {
            copy(isShowGuide = isShow)
        }
    }

    fun setVibratorEnable(enable: Boolean) {
        spVibratorEnable = enable
        setState { copy(vibratorEnable = enable) }
    }

    override fun onCleared() {
        val state = this.state
        spIsShowGuide = state.isShowGuide
        spKeepScreenOn = state.keepScreenOn
        super.onCleared()
    }

    companion object : MvRxViewModelFactory<SettingsViewModel, SettingsState> {
        override fun create(
            viewModelContext: ViewModelContext,
            state: SettingsState
        ): SettingsViewModel? {
            val context = viewModelContext.activity.applicationContext
            return SettingsViewModel(state, context)
        }
    }
}